package com.cn.netty.basic;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

@Slf4j
public class EchoClient {
  public static void main(String[] args) {
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .remoteAddress(new InetSocketAddress("127.0.0.1", 9999))
            .handler(new ChannelInitializer<SocketChannel>() {//这里是个handler
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler());
                    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, EchoServer.delimiter)); //入站 粘包拆包问题
                    ch.pipeline().addLast(new EchoClientHandler());
                }
            });

    try {

      ChannelFuture sync = bootstrap.connect().sync();
//      sync.channel().closeFuture().sync();
//      eventLoopGroup.shutdownGracefully(1,10, TimeUnit.SECONDS);
        Channel channel = sync.channel();
        log.info("channel -> {}",channel);
        log.info("链接已经建立,准备关闭");
        ChannelFuture channelFuture = channel.closeFuture();
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("优雅关闭");
                eventLoopGroup.shutdownGracefully(1,10, TimeUnit.SECONDS);
            }
        });

        log.info("main end");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}
